<?php

namespace Shop\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Shop\AdminBundle\Controller\BaseController;

use Shop\AdminBundle\Entity\Product;
use Shop\AdminBundle\Form\ProductType;

/**
 * Product controller.
 *
 * @Route("/admin/product")
 */
class ProductController extends BaseController
{

    /**
     * @Route("/", name="admin_product")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $repo=$this->getRepo('product');
        return $this->paginate($repo);
    }

    /**
     * 添加商品，表单处理
     *
     * @Route("/", name="admin_product_create")
     * @Method("POST")
     */
    public function createAction(Request $request)
    {
        $entity = new Product();
        $form = $this->createForm(new ProductType(), $entity, array(
            'action' => $this->generateUrl('admin_product_create'),
            'method' => 'POST',
        ));

        $form->handleRequest($request);

        //TODO:添加可选字段
        $this->setOptional($entity, [
            'countSold',
            'enableShopCart',
            'enablePhoneVerify'
        ]);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $reqData=$request->request->get('shop_adminbundle_product');
            if(isset($reqData['enableShopCart'])){
                $entity->setEnableShopCart(1);
            }
            if(isset($reqData['enablePhoneVerify'])){
                $entity->setEnablePhoneVerify(1);
            }

            //set discount
            $entity->setDiscount(round( ($entity->getPrice() / $entity->getOriginPrice()), 1) );

            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_product'));
        }

        return $this->redirect($this->generateUrl('admin_product_new'));
    }

    /**
     * 添加商品页面
     *
     * @Route("/new", name="admin_product_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Product();
        $form = $this->createForm(new ProductType(), $entity, array(
            'action' => $this->generateUrl('admin_product_create'),
            'method' => 'POST',
        ));

        //门店列表
        $shopList=$this->getAvailableList('shop');
        //品牌列表
        $brandList=$this->getAvailableList('brand');

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'shopList'=> $shopList,
            'brandList'=> $brandList,
            'ajax_form'=>true

        );
    }

    /**
     * 编辑商品页面
     *
     * @Route("/{id}/edit", name="admin_product_edit")
     * @Method("GET")
     * @Template("ShopAdminBundle:Product:new.html.twig")
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ShopAdminBundle:Product')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Product entity.');
        }

        $editForm = $this->createForm(new ProductType(), $entity, array(
            'action' => $this->generateUrl('admin_product_update', array('id' => $entity->getId())),
            'method' => 'POST',
        ));

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'shopList'=>$this->getAvailableList('shop'),
            'brandList'=>$this->getAvailableList('brand'),
            'is_edit'=>true,
            'ajax_form'=>true
        );
    }

    /**
     * 更新商品，表单处理
     *
     * @Route("/{id}", name="admin_product_update")
     * @Method("POST")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ShopAdminBundle:Product')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Product entity.');
        }

        $editForm = $this->createForm(new ProductType(), $entity, array(
            'action' => $this->generateUrl('admin_product_update', array('id' => $entity->getId())),
            'method' => 'POST',
        ));

        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $reqData=$request->request->get('shop_adminbundle_product');
            if(isset($reqData['enableShopCart'])){
                $entity->setEnableShopCart(1);
            }
            if(isset($reqData['enablePhoneVerify'])){
                $entity->setEnablePhoneVerify(1);
            }

            //set discount
            $entity->setDiscount(round( ($entity->getPrice() / $entity->getOriginPrice()), 1) );

            $em->flush();
            return $this->redirect($this->generateUrl('admin_product'));
        }
    }

    /**
     * Deletes a Product entity.
     *
     * @Route("/{id}/delete", name="admin_product_delete")
     * @Method("GET")
     */
    public function deleteAction(Request $request, $id)
    {
        return $this->deleteRow('product',$request, $id);
    }
}
